<?php

Class Router {

	/*
	* @the registry
	*/

	private $registry;

	/*
	* @the controller path
	*/	

	private $path;

	private $args = array();

	private $file;

	private $controller;

	private $action;

	function __construct($registry){
		
		$this->registry = $registry;

	}

	/**
	*
	* @set controller directory path
	*
	* @param string $path
	*
	* @return void
	*
	*/

	function setPath($path){

		/*** check if path is a directory ***/
		if(is_dir($path) == false){
		
			throw new Exception ('Invalid controller path: `' .$path.'`');
	
		}
		
		/*** set the path ***/
		$this->path = $path;		
			
	}
	
	/**
	*
	* @load the controller
	*
	* @access public
	*
	* @return void
	*
	*/

	public function loader(){
	
		/*** check the route ***/
		$this->getController();

		/*** if the file isn't found or read-protected ***/
		if(is_readable($this->file) == false){
		
			print $this->file;
			die('404 - Not found.'); //And perhaps a redirection to a custom 404 page.		
			
		}

		/*** include the controller ***/
		include $this->file;
		
		/*** instantiate the controller ***/
		$class = $this->controller . 'Controller';
		$controller = new $class($this->registry);
		
		/*** check if the action is callable ***/
		if(is_callable(array($controller, $this->action)) == false){
			$action = 'render';
		
		} else {
		
			$action = $this->action;	
		
		}
		
		/*** run the action ***/
		$controller->$action();
		
	}
	
	/**
	*
	* @get the controller
	*
	* @access private
	*
	* @return void
	*
	*/
	
	private function getController(){
	
		/*** get the route from url ***/
		$route = (empty($_GET['rt'])) ? '' : $_GET['rt'];
		
		if(empty($route)){
		
			$route = 'index';
		
		} else {
			
			/*** split the route into parts ***/
			$parts = explode('/', $route);
			$this->controller = ucwords($parts[0]);
			if(isset($parts[1])){
			
				$this->action = $parts[1];
			
			}	
			
		}
		
		if(empty($this->controller)){
		
			$this->controller = 'Index';
		
		}	
		
		/*** get action ***/
		if(empty($this->action)){
		
			$this->action = 'show';
		
		}
	
	
		/*** set file path ***/
		$this->file = $this->path . '/' . $this->controller . 'Controller' . '.php';	
	
	}
	

}

